package com.shoux.api.tools;

import com.alibaba.fastjson.JSONObject;
import com.shoux.api.config.MyApiProperties;
import com.shoux.api.web.entity.apiData.PostResEntity;
import com.shoux.api.web.service.apiData.PostResService;
import org.apache.hadoop.hbase.shaded.com.google.gson.JsonObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponents;
import org.springframework.web.util.UriComponentsBuilder;

import javax.annotation.Resource;
import java.net.URI;

/**
 * Created with IntelliJ IDEA.
 * User: xiaoZhi
 * Date: 2022/3/25
 * Time: 16:52
 * Description:
 */
@Component
public class RestTemplateUtil {

    @Autowired
    private RestTemplate restTemplate;
    @Resource
    private MyApiProperties myApiProperties;

    @Value("${my-api.ansuo.url}")
    private String url;

    @Autowired
    private PostResService postResService;

    public JSONObject getBody(JSONObject params, String transcode, String interfaceDesc) {
        myApiProperties.setParams(params);
        myApiProperties.setTranscode(transcode);

        JSONObject jsonObject = (JSONObject) JSONObject.toJSON(myApiProperties);
        UriComponents uriComponents = UriComponentsBuilder.fromUriString(url).build(true);
        URI uri = uriComponents.toUri();

        RequestEntity<JSONObject> requestEntity = RequestEntity.post(uri).
                header("Content-Type", "application/json;charset=utf-8").
                body(jsonObject);
        ResponseEntity<JSONObject> responseEntity = restTemplate.exchange(requestEntity, JSONObject.class);
        // 响应结果
        JSONObject responseEntityBody = responseEntity.getBody();
        if ("淄博工商综合信息查询".equals(interfaceDesc)) {
            PostResEntity postResEntity = new PostResEntity();
            postResEntity.setPostname(interfaceDesc);
            postResEntity.setParams(jsonObject.toJSONString());
            postResEntity.setResponse(responseEntityBody.toJSONString());
            postResEntity.setStatus(0);
            try {
                postResService.save(postResEntity);
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("工商信息入库失败！但不影响接口返回。");
            }
        }
        return responseEntityBody;
    }
}
